package com.jz.digital.scan

import android.Manifest
import android.app.Activity
import android.view.MotionEvent
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import androidx.core.app.ActivityCompat
import com.jz.digital.R
import com.jz.digital.base.BaseActivity
import com.jz.digital.dialog.CommBottomConfirmDialog.Companion.newInstance
import com.jz.digital.utils.LogUtils
import com.jz.digital.utils.PermissionUtil
import com.jz.digital.utils.PermissionUtil.RequestResult
import com.king.zxing.CaptureHelper
import com.king.zxing.OnCaptureCallback
import com.king.zxing.ViewfinderView
import kotlinx.android.synthetic.main.activity_scan_code.iv_torch
import kotlinx.android.synthetic.main.activity_scan_code.title_leftBtn
import kotlinx.android.synthetic.main.activity_scan_code.tv_light
import kotlinx.android.synthetic.main.activity_scan_code.tv_scan_not_find

/**
 * @Author: ym
 * @ClassName: ScanCodeActivity
 * @Description: 二维码扫描界面
 * @Package: com.ido.life.module.bind
 * @CreateDate: 2020-03-18 19:49
 */
class ScanCodeActivity : BaseActivity<ScanCodePresenter>(), IScanView, RequestResult,
    OnCaptureCallback {
        private val tag="ScanCodeActivity"

    /**
     * 权限工具类
     */
    private var permissionUtil: PermissionUtil? = null

    private var surfaceView: SurfaceView? = null
    private var viewfinderView: ViewfinderView? = null

    private var mCaptureHelper: CaptureHelper? = null

    private var surfaceHolder: SurfaceHolder? = null

    public override fun initViews() {
        super.initViews()
        initUI()
        tv_light.text = getString(R.string.key_465)
        tv_scan_not_find.text = getString(R.string.key_745)
    }

    /**
     * 初始化扫描
     */
    private fun initCapture() {
        mCaptureHelper!!.onCreate()
    }

    /**
     * 初始化
     */
    fun initUI() {
        surfaceView = findViewById(R.id.surfaceView)
        viewfinderView = findViewById(R.id.viewfinderView)
        iv_torch!!.visibility = View.VISIBLE


        if (surfaceHolder == null) {
            surfaceHolder = surfaceView!!.getHolder()
        }
        mCaptureHelper = CaptureHelper(this, surfaceView, viewfinderView, iv_torch)
        mCaptureHelper!!.setOnCaptureCallback(this)
        initCapture()
        title_leftBtn?.setOnClickListener { supportFinishAfterTransition() }
    }


    override fun initData() {
        permissionUtil = PermissionUtil()
        permissionUtil!!.setRequestResult(this)
        //判断权限相机权限是否打开
        val cameraPermission1 = PermissionUtil.getCameraPermission()
        if (!checkPermission(*cameraPermission1)) {
            //扫描到二维码之后再扫描周边设备
            //未打开存储权限暂不处理
            if (isDeniedByNoAsk(*PermissionUtil.getOnlyCameraPermission())) {
                val cameraPermission = PermissionUtil.getCameraPermission()
                requestPermissions(CAMERA_REQUEST_CODE, *cameraPermission)
            } else {
                showOpenCameraDialog()
            }
        }
    }

    /**
     * 是否点击了不再询问
     *
     * @param permissions
     * @return
     */
    private fun isDeniedByNoAsk(vararg permissions: String): Boolean {
        var isDeniedByNoAsk = false
        for (i in permissions.indices) {
            if (!ActivityCompat.shouldShowRequestPermissionRationale(
                    this@ScanCodeActivity,
                    permissions[i]
                )
            ) { //返回 false 就表示勾选了不再询问
                isDeniedByNoAsk = true
                break
            }
        }
        return isDeniedByNoAsk
    }

    /**
     * 用户禁止了相机权限
     */
    private fun showOpenCameraDialog() {
        val dialog = newInstance(
            getString(R.string.key_1132),
            getString(R.string.key_1350), getString(R.string.key_744),
            getString(R.string.key_507), false
        )
        dialog.setOnConfirmListener { v: View? ->
            dialog.dismissAllowingStateLoss()
            supportFinishAfterTransition()
        }
        dialog.show(supportFragmentManager)
    }


    override fun getLayoutResId(): Int {
        return R.layout.activity_scan_code
    }

    override fun requestPermissions(requestCode: Int, vararg permissions: String) {
        PermissionUtil.requestPermissions(this, requestCode, *permissions)
    }

    fun checkPermission(vararg permissions: String?): Boolean {
        return PermissionUtil.checkSelfPermission(this, *permissions)
    }

    public override fun onResume() {
        super.onResume()
        if (checkSelfPermission(*arrayOf(Manifest.permission.CAMERA))) {
            if (mCaptureHelper != null) {
                mCaptureHelper!!.onResume()
            }
        }
    }

    public override fun onPause() {
        super.onPause()
        if (mCaptureHelper != null) {
            mCaptureHelper!!.onPause()
        }
    }

    public override fun onDestroy() {
        super.onDestroy()
        if (mCaptureHelper != null) {
            mCaptureHelper!!.onDestroy()
        }
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        mCaptureHelper!!.onTouchEvent(event)
        return super.onTouchEvent(event)
    }


    override fun onRequestPermissionsResult(
        requestCode: Int, permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        permissionUtil!!.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    override fun requestPermissionsSuccess(requestCode: Int) {
        initCapture()
        mCaptureHelper!!.onResume()
        mCaptureHelper!!.initCamera(surfaceHolder)
    }

    override fun requestPermissionsFail(requestCode: Int) {
        LogUtils.d(tag,"相机权限请求失败")
        supportFinishAfterTransition()
    }

    override fun onResultCallback(result: String?): Boolean {
        if (result.isNullOrEmpty()) return false
        setResult(Activity.RESULT_OK, intent.putExtra(KEY_DATA, result))
        finish()
        return true
    }


    companion object {
        const val KEY_DATA = "key_data"

        /**
         * 相机权限
         */
        const val CAMERA_REQUEST_CODE: Int = 10002
    }
}
